#!/usr/bin/env node
import minimist from 'minimist'
import path from 'node:path'
import {autoConf} from 'auto-config-loader'
import {run, helpStr, __filename, pkg} from './utils/utils.js'
import type {Options, Config} from './utils/utils.js'
import watch from './watch.js'
import {startServe} from './server.js'
;(async () => {
    try {
        const argvs: Options = minimist(process.argv.slice(2), {
            alias: {
                watch: 'w',
                build: 'b',
                force: 'f',
                // 辅助指令
                version: 'v',
                help: 'h',
            },
            default: {
                watch: false,
                build: true,
                force: false,
            },
        })
        if (argvs.v || argvs.version) {
            return console.log(`v${pkg.version}`)
        }
        if (argvs.h || argvs.help) {
            return console.log(helpStr)
        }

        argvs.static_path = path.join(__filename, '../../../static')

        const conf = await autoConf<Config>('refs', {
            mustExist: false,
        })
        argvs.config = conf || {}
        argvs.config.outputPath = path.resolve(process.cwd(), conf.outputDir || 'docs')
        argvs.config.inputPath = path.resolve(process.cwd(), conf.inputDir || 'refs')
        argvs.config.attachmentPath = path.resolve(process.cwd(), conf.attachmentDir || 'attachments')

        if (argvs.watch) {
            await watch(argvs)
            if (argvs.config.server) {
                startServe(argvs)
            }
        } else if (argvs.build) {
            await run(argvs)
        }
    } catch (error) {
        if (error instanceof Error) {
            console.log('REFS:', error.message)
            console.log('REFS:', error)
            console.log(helpStr)
        }
    }
})()
